package yzbx.personalwebsite.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import yzbx.personalwebsite.config.ConfigData;
import yzbx.personalwebsite.entity.*;
import yzbx.personalwebsite.entityWeb.*;
import yzbx.personalwebsite.service.CommonService;
import yzbx.personalwebsite.service.GetServerInfo;
import yzbx.personalwebsite.tool.utilTool;
import yzbx.personalwebsite.webSocket.WebSocketTalk;

import java.util.Map;

import static yzbx.personalwebsite.config.Constants.*;

/**
 * {@code @Author} zxm
 * {@code @Description} 通用控制层
 * {@code @Date} 2024/10/11/16:33
 * {@code @Version} 1.0
 */
@Controller
@RequestMapping("/common")
public class CommonController {

    private static final Logger LOGGER = LoggerFactory.getLogger(CommonController.class);

    private final CommonService commonService;
    private final GetServerInfo getServerInfo;
    private final ConfigData configData;
    private final WebSocketTalk webSocketTalk;

    public CommonController(CommonService commonService, GetServerInfo getServerInfo, ConfigData configData, WebSocketTalk webSocketTalk) {
        this.commonService = commonService;
        this.getServerInfo = getServerInfo;
        this.configData = configData;
        this.webSocketTalk = webSocketTalk;
    }

    @RequestMapping("/getUsefWebs")
    @ResponseBody
    public HttpResponse getUsefWebs() {
        return HttpResponse.success(commonService.getUsefWebs());
    }

    @RequestMapping("/addUsefWebs")
    @ResponseBody
    public HttpResponse addUsefWebs(@RequestParam(value = "file", required = false) MultipartFile file,
                                    @RequestParam("title") String title,
                                    @RequestParam("description") String description,
                                    @RequestParam("url") String url,
                                    @RequestParam("group") String group
    ) {
        if (file == null || file.isEmpty() || file.getOriginalFilename() == null) {
            LOGGER.info("文件为空");
            return new HttpResponse(HTTP_CODE_511, HTTP_CODE_511_MSG, null);
        }
        if (title.trim().isEmpty()) {
            return new HttpResponse(HTTP_CODE_512, "名称" + HTTP_CODE_512_MSG, null);
        }
        if (url.trim().isEmpty()) {
            return new HttpResponse(HTTP_CODE_512, "链接" + HTTP_CODE_512_MSG, null);
        }
        if (group.trim().isEmpty()) {
            return new HttpResponse(HTTP_CODE_512, "分组" + HTTP_CODE_512_MSG, null);
        }
        String fileName = title + utilTool.getRandomId(8) + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        utilTool.saveImg(file, configData.getUsefWebsPath(), fileName);

        UsefWebsEntity usefWebsEntity = new UsefWebsEntity();
        usefWebsEntity.setTitle(title);
        usefWebsEntity.setDescription(description);
        usefWebsEntity.setUrl(url);
        usefWebsEntity.setImg(fileName);
        usefWebsEntity.setGroup(group);
        commonService.addUsefWebs(usefWebsEntity);
        return HttpResponse.success(null);
    }

    @RequestMapping("/updUsefWebs")
    @ResponseBody
    public HttpResponse updUsefWebs(
            @RequestParam("sort") String sort,
            @RequestParam(value = "file", required = false) MultipartFile file,
            @RequestParam("title") String title,
            @RequestParam("description") String description,
            @RequestParam("url") String url,
            @RequestParam("group") String group
    ) {
        String fileName = "";
        if (file == null || file.isEmpty() || file.getOriginalFilename() == null) {
            LOGGER.info("文件为空,无需更新图片");
        } else {
            fileName = title + utilTool.getRandomId(8) + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            utilTool.saveImg(file, configData.getUsefWebsPath(), fileName);
        }
        UsefWebsEntity usefWebsEntity = new UsefWebsEntity();
        usefWebsEntity.setSort(Integer.parseInt(sort));
        usefWebsEntity.setTitle(title);
        usefWebsEntity.setDescription(description);
        usefWebsEntity.setUrl(url);
        usefWebsEntity.setImg(fileName);
        usefWebsEntity.setGroup(group);
        commonService.updUsefWebs(usefWebsEntity);
        return HttpResponse.success(null);
    }


    @RequestMapping("/delUsefWebs")
    @ResponseBody
    public HttpResponse delUsefWebs(@RequestBody() UsefWebsEntity usefWebsEntity) {
        commonService.delUsefWebs(usefWebsEntity);
        return HttpResponse.success(null);
    }

    @RequestMapping("/getWebLog")
    @ResponseBody
    public HttpResponse getWebLog() {
        return HttpResponse.success(commonService.getWebLog());
    }

    @RequestMapping("/addWebLog")
    @ResponseBody
    public HttpResponse addWebLog(@RequestBody() WebLogEntity weblog) {
        commonService.addWebLog(weblog);
        return HttpResponse.success(null);
    }

    @RequestMapping("/delWebLog")
    @ResponseBody
    public HttpResponse delWebLog(@RequestBody() WebLogEntity weblog) {
        commonService.delWebLog(weblog);
        return HttpResponse.success(null);
    }

    @RequestMapping("/getRecoIdea")
    @ResponseBody
    public HttpResponse getRecoIdea(@RequestBody() SessionRequst sessionRequst) {
        String author = "";
        UserEntity userEntity = commonService.getUserInfo(sessionRequst.getSession());
        if (userEntity != null) {
            author = userEntity.getName();
        }
        return HttpResponse.success(commonService.getRecoIdea(author));
    }

    @RequestMapping("/getRecoIdeaById")
    @ResponseBody
    public HttpResponse getRecoIdeaById(@RequestBody() RecoIdeaWithUserRequst recoIdeaWithUserRequst) {
        SessionRequst sessionRequst = recoIdeaWithUserRequst.getSessionRequst();
        UserEntity userEntity = commonService.getUserInfo(sessionRequst.getSession());
        if (userEntity == null) {
            return new HttpResponse(HTTP_CODE_504, HTTP_CODE_504_MSG, null);
        }
        RecoIdeaEntity recoIdeaEntity = recoIdeaWithUserRequst.getRecoIdeaEntity();
        RecoIdeaEntity recoIdea = commonService.getRecoIdeaById(recoIdeaEntity.getId(), userEntity.getName());
        if (recoIdea == null) {
            return new HttpResponse(HTTP_CODE_510, HTTP_CODE_510_MSG, null);
        }
        return HttpResponse.success(recoIdea);
    }

    @RequestMapping("/addRecoIdea")
    @ResponseBody
    public HttpResponse addRecoIdea(@RequestBody() RecoIdeaWithUserRequst recoIdeaWithUserRequst) {
        SessionRequst sessionRequst = recoIdeaWithUserRequst.getSessionRequst();
        UserEntity userEntity = commonService.getUserInfo(sessionRequst.getSession());
        if (userEntity == null) {
            return new HttpResponse(HTTP_CODE_504, HTTP_CODE_504_MSG, null);
        }
        RecoIdeaEntity recoIdeaEntity = recoIdeaWithUserRequst.getRecoIdeaEntity();
        recoIdeaEntity.setAuthor(userEntity.getName());
        recoIdeaEntity.setAuthorId(userEntity.getId());
        commonService.addRecoIdea(recoIdeaEntity);
        return HttpResponse.success(null);
    }

    @RequestMapping("/delRecoIdea")
    @ResponseBody
    public HttpResponse delRecoIdea(@RequestBody() RecoIdeaWithUserRequst recoIdeaWithUserRequst) {
        SessionRequst sessionRequst = recoIdeaWithUserRequst.getSessionRequst();
        UserEntity userEntity = commonService.getUserInfo(sessionRequst.getSession());
        if (userEntity == null) {
            return new HttpResponse(HTTP_CODE_504, HTTP_CODE_504_MSG, null);
        }
        RecoIdeaEntity recoIdeaEntity = recoIdeaWithUserRequst.getRecoIdeaEntity();
        recoIdeaEntity.setAuthor(userEntity.getName());
        commonService.delRecoIdea(recoIdeaEntity);
        return HttpResponse.success(null);
    }

    @RequestMapping("/saveImgToHost")
    @ResponseBody
    public Map<String, Object> getImg(@RequestParam("imgName") MultipartFile file) {
        if (file.isEmpty() || file.getOriginalFilename() == null) {
            LOGGER.info("图片为空");
            return WangImgResponse.setFailResponse();
        }
        String fn = file.getOriginalFilename();
        String fileName = fn.substring(0, fn.lastIndexOf(".")) + utilTool.getRandomId(8) + fn.substring(fn.lastIndexOf("."));
        utilTool.saveImg(file, configData.getWangPath(), fileName);
        return WangImgResponse.setSimpleResponse(configData.getWangPathLocal() + fileName);
    }

    @RequestMapping("/getUsefWebsGroup")
    @ResponseBody
    public HttpResponse getUsefWebsGroup() {
        return HttpResponse.success(commonService.getUsefWebsGroup());
    }

    @RequestMapping("/addUsefWebsGroup")
    @ResponseBody
    public HttpResponse addUsefWebsGroup(@RequestBody() UsefWebsGroupEntity usefWebsGroupEntity) {
        commonService.addUsefWebsGroup(usefWebsGroupEntity);
        return HttpResponse.success(null);
    }

    @RequestMapping("/delUsefWebsGroup")
    @ResponseBody
    public HttpResponse delUsefWebsGroup(@RequestBody() UsefWebsGroupEntity usefWebsGroupEntity) {
        commonService.delUsefWebsGroup(usefWebsGroupEntity);
        return HttpResponse.success(null);
    }

    @RequestMapping("/getUsefWebsUsesVisitRank")
    @ResponseBody
    public HttpResponse getUsefWebsUsesVisitRank() {
        return HttpResponse.success(commonService.getUsefWebsUsesVisitRank());
    }

    @RequestMapping("/addUsefWebsUsesVisitRank")
    @ResponseBody
    public HttpResponse addUsefWebsUsesVisitRank(@RequestBody() UsefWebsUsesVisitRankEntity usefWebsUsesVisitRankEntity) {
        commonService.addUsefWebsUsesVisitRank(usefWebsUsesVisitRankEntity);
        return HttpResponse.success(null);
    }

    @RequestMapping("/getServerInfo")
    @ResponseBody
    public HttpResponse getServerInfo() {
        return HttpResponse.success(getServerInfo.getServerInfo());
    }

    @RequestMapping("/addTalkRecord")
    @ResponseBody
    public HttpResponse addTalkRecord(@RequestBody() TalkRecordWithUserRequst talkRecordWithUserRequst) {
        SessionRequst sessionRequst = talkRecordWithUserRequst.getSessionRequst();
        UserEntity userEntity = commonService.getUserInfo(sessionRequst.getSession());
        if (userEntity == null) {
            return new HttpResponse(HTTP_CODE_504, HTTP_CODE_504_MSG, null);
        }
        TalkRecordEntity talkRecordEntity = talkRecordWithUserRequst.getTalkRecordEntity();
        talkRecordEntity.setAuthorName(userEntity.getName());
        talkRecordEntity.setAuthorId(userEntity.getId());
        talkRecordEntity.setAuthorTx(userEntity.getTx());
        commonService.addTalkRecord(talkRecordEntity);
        // 调用webSocket通知客户端拉取新信息
        webSocketTalk.sendMessageToAll();
        return HttpResponse.success(null);
    }

    @RequestMapping("/getTalkRecord")
    @ResponseBody
    public HttpResponse getTalkRecord(@RequestBody() TalkRecordEntity talkRecordEntity) {
        return HttpResponse.success(commonService.getTalkRecord(talkRecordEntity.getTalkRoomId()));
    }

    @RequestMapping("/getTalkRoom")
    @ResponseBody
    public HttpResponse getTalkRoom() {
        return HttpResponse.success(commonService.getTalkRoom());
    }
}
